package com.gftBrazil.BankSystem.view;

import com.gftBrazil.BankSystem.bean.AgenciaBean;
import com.gftBrazil.BankSystem.business.AgenciaBusiness;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.ParseException;
import javax.swing.JOptionPane;
import javax.swing.text.DefaultFormatterFactory;

/**
 *
 * @author JRSS
 */
public class AgenciaView extends javax.swing.JInternalFrame {

    /**
     * Creates new form AgenciaView
     */
    public AgenciaView() {
        this.agencia = new AgenciaBean();
        initComponents();
        initListeners();
        preparaCampos();
    }

    public AgenciaView(boolean novaAgencia) {
        this.agencia = new AgenciaBean();
        initComponents();
        preparaCampos();
        if (novaAgencia) {
            tCodigoAgencia.setEnabled(false);
            bConsultarAgencia.setEnabled(false);
        } else {
            tNomeAgencia.requestFocus();
            tNomeAgencia.setEnabled(false);
            tCnpjAgencia.setEnabled(false);
            tEnderecoAgencia.setEnabled(false);
            bSalvar.setEnabled(false);
        }
        initListeners();
    }

    private void initListeners() {
        this.bConsultarAgencia.addActionListener(trataBotoes);
        this.bSalvar.addActionListener(trataBotoes);
        this.bDesativar.addActionListener(trataBotoes);
        this.bReativar.addActionListener(trataBotoes);
        this.bLimpar.addActionListener(trataBotoes);

        this.tCodigoAgencia.addFocusListener(trataFoco);
        this.tNomeAgencia.addFocusListener(trataFoco);
        this.tCnpjAgencia.addFocusListener(trataFoco);
        this.tEnderecoAgencia.addFocusListener(trataFoco);
        this.ckAgenciaAtiva.addFocusListener(trataFoco);

        this.tCodigoAgencia.addKeyListener(trataTeclas);
        this.bConsultarAgencia.addKeyListener(trataTeclas);
        this.tNomeAgencia.addKeyListener(trataTeclas);
        this.tCnpjAgencia.addKeyListener(trataTeclas);
        this.ckAgenciaAtiva.addKeyListener(trataTeclas);
        this.tEnderecoAgencia.addKeyListener(trataTeclas);
        this.bSalvar.addKeyListener(trataTeclas);
    }

    private void preparaCampos() {
        javax.swing.text.MaskFormatter format;
        try {
            format = new javax.swing.text.MaskFormatter("##.###.###/####-##");
            tCnpjAgencia.setFormatterFactory(new DefaultFormatterFactory(format));
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(getParent(), "Erro ao atribuir mascara ao campo", "Mascara CNPJ", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        lCodigoAgencia = new javax.swing.JLabel();
        tCodigoAgencia = new javax.swing.JTextField();
        bConsultarAgencia = new javax.swing.JButton();
        pAgencia = new javax.swing.JPanel();
        lNomeAgencia = new javax.swing.JLabel();
        tNomeAgencia = new javax.swing.JTextField();
        lCnpjAgencia = new javax.swing.JLabel();
        lEnderecoAgencia = new javax.swing.JLabel();
        ckAgenciaAtiva = new javax.swing.JCheckBox();
        tEnderecoAgencia = new javax.swing.JTextField();
        tCnpjAgencia = new javax.swing.JFormattedTextField();
        pButtons = new javax.swing.JPanel();
        bSalvar = new javax.swing.JButton();
        bDesativar = new javax.swing.JButton();
        bReativar = new javax.swing.JButton();
        bLimpar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        tMensagem = new javax.swing.JLabel();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Agencia View");
        setPreferredSize(new java.awt.Dimension(600, 200));
        getContentPane().setLayout(new java.awt.GridBagLayout());

        lCodigoAgencia.setText("Codigo Agencia:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0);
        getContentPane().add(lCodigoAgencia, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        getContentPane().add(tCodigoAgencia, gridBagConstraints);

        bConsultarAgencia.setText("Consultar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
        getContentPane().add(bConsultarAgencia, gridBagConstraints);

        pAgencia.setLayout(new java.awt.GridBagLayout());

        lNomeAgencia.setText("Nome:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        pAgencia.add(lNomeAgencia, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        pAgencia.add(tNomeAgencia, gridBagConstraints);

        lCnpjAgencia.setText("CNPJ:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        pAgencia.add(lCnpjAgencia, gridBagConstraints);

        lEnderecoAgencia.setText("Endereco:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        pAgencia.add(lEnderecoAgencia, gridBagConstraints);

        ckAgenciaAtiva.setText("Agencia ativa");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        pAgencia.add(ckAgenciaAtiva, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        pAgencia.add(tEnderecoAgencia, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        pAgencia.add(tCnpjAgencia, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 5.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 2, 4, 2);
        getContentPane().add(pAgencia, gridBagConstraints);

        pButtons.setLayout(new java.awt.GridBagLayout());

        bSalvar.setText("Salvar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        pButtons.add(bSalvar, gridBagConstraints);

        bDesativar.setText("Desativar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        pButtons.add(bDesativar, gridBagConstraints);

        bReativar.setText("Reativar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        pButtons.add(bReativar, gridBagConstraints);

        bLimpar.setText("Limpar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        pButtons.add(bLimpar, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 2;
        getContentPane().add(pButtons, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        getContentPane().add(jSeparator1, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        getContentPane().add(jSeparator2, gridBagConstraints);

        tMensagem.setText(" ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0);
        getContentPane().add(tMensagem, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

//    /**
//     * @param args the command line arguments
//     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(AgenciaView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            @Override
//            public void run() {
//                new AgenciaView().setVisible(true);
//            }
//        });
//    }
    private void mostra() {
        if (agencia != null) {
            tCodigoAgencia.setText(String.valueOf(agencia.getCodigoAgencia()));
            tNomeAgencia.setText(agencia.getNome());
            tCnpjAgencia.setText(agencia.getCnpj());
            tEnderecoAgencia.setText(agencia.getEndereco());
            ckAgenciaAtiva.setSelected(agencia.isAtiva());
        }
    }

    private void limpar() {
        tCodigoAgencia.setText("");
        tNomeAgencia.setText("");
        tCnpjAgencia.setText("");
        tEnderecoAgencia.setText("");
        ckAgenciaAtiva.setSelected(false);
    }

    private boolean salvar() {
        boolean sucess;
        AgenciaBusiness.setAgencia(agencia);
        sucess = AgenciaBusiness.getInstance().cadastrarAgencia(agencia);
        agencia = new AgenciaBean();
        return sucess;
    }

    private void consultar() {
        if (!tCodigoAgencia.getText().equals("")) {
            int agenciaCodigo = Integer.valueOf(tCodigoAgencia.getText());
            agencia = AgenciaBusiness.getInstance().consultarAgencia(agenciaCodigo);
            if (agencia == null) {
                tMensagem.setText("Nao ha agencia com este codigo!");
                limpar();
            }
        }
    }

    private boolean desativar() {
        boolean sucess;
        int agenciaCodigo = Integer.valueOf(tCodigoAgencia.getText());
        agencia = AgenciaBusiness.getInstance().consultarAgencia(agenciaCodigo);
        if (agencia.getCodigoAgencia() == 0) {
            sucess = false;
        } else {
            sucess = AgenciaBusiness.getInstance().desativarAgencia(agenciaCodigo);
        }
        return sucess;
    }

    private boolean reativar() {
        boolean sucess;
        int agenciaCodigo = Integer.valueOf(tCodigoAgencia.getText());
        agencia = AgenciaBusiness.getInstance().consultarAgencia(agenciaCodigo);
        if (agencia.getCodigoAgencia() == 0) {
            sucess = false;
        } else {
            sucess = AgenciaBusiness.getInstance().reativarAgencia(agenciaCodigo);
        }
        return sucess;
    }

    private class TrataBotoes implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (ae.getSource() == bConsultarAgencia) {
                if (agencia.getCodigoAgencia() == 0) {
                    tMensagem.setText("Codigo de agencia invalido!");
                } else {
                    if (!AgenciaBusiness.getInstance().getAgencias().isEmpty()) {
                        consultar();
                        mostra();
                        agencia = new AgenciaBean();
                    } else {
                        tMensagem.setText("Nao ha agencia cadastrata!");
                    }
                }
            } else if (ae.getSource() == bSalvar) {
                if (!salvar()) {
                    tMensagem.setText("Informacoes invalidas!");
                } else {
                    tMensagem.setText("Agencia cadastrada com sucesso!");
                }
                mostra();
            } else if (ae.getSource() == bDesativar) {
                if (desativar()) {
                    consultar();
                    tMensagem.setText("Agencia desativada com sucesso!");
                } else {
                    tMensagem.setText("Agencia NAO desativada sucesso!");
                }
                mostra();
                agencia = new AgenciaBean();
            } else if (ae.getSource() == bReativar) {
                if (reativar()) {
                    consultar();
                    tMensagem.setText("Agencia ativada com sucesso!");
                } else {
                    tMensagem.setText("Agencia NAO ativada sucesso!");
                }
                mostra();
                agencia = new AgenciaBean();
            } else if (ae.getSource() == bLimpar) {
                limpar();
            }
        }
    }

    private class TrataFoco implements FocusListener {

        @Override
        public void focusGained(FocusEvent fe) {
        }

        @Override
        public void focusLost(FocusEvent fe) {
            if (agencia == null) {
                agencia = new AgenciaBean();
            }
            String value;
            if (fe.getSource() == tCodigoAgencia) {
                value = tCodigoAgencia.getText();
                if (!value.equals("")) {
                    try {
                        int codigoAgencia = Integer.valueOf(value);
                        agencia.setCodigoAgencia(codigoAgencia);
                    } catch (NumberFormatException ex) {
                        tMensagem.setText("Agencia invalida!");
                    }
                }
            } else if (fe.getSource() == tNomeAgencia) {
                value = tNomeAgencia.getText();
                if (!value.equals("")) {
                    agencia.setNome(value);
                }
            } else if (fe.getSource() == tCnpjAgencia) {
                value = tCnpjAgencia.getText();
                if (!value.equals("")) {
                    agencia.setCnpj(value);
                }
            } else if (fe.getSource() == tEnderecoAgencia) {
                value = tEnderecoAgencia.getText();
                if (!value.equals("")) {
                    agencia.setEndereco(value);
                }
            } else if (fe.getSource() == ckAgenciaAtiva) {
                boolean isAtiva = ckAgenciaAtiva.isSelected();
                agencia.setAtiva(isAtiva);
            }
        }
    }

    private class TrataTeclas implements KeyListener {

        @Override
        public void keyTyped(KeyEvent ke) {

        }

        @Override
        public void keyPressed(KeyEvent ke) {
            if (ke.getKeyCode() == KeyEvent.VK_ENTER || ke.getKeyCode() == KeyEvent.VK_TAB) {
                if (ke.getSource() == tCodigoAgencia) {
                    bConsultarAgencia.requestFocus();
                } else if (ke.getSource() == bConsultarAgencia) {
                    consultar();
                    mostra();
                    agencia = new AgenciaBean();
                } else if (ke.getSource() == tNomeAgencia) {
                    tCnpjAgencia.requestFocus();
                } else if (ke.getSource() == tCnpjAgencia){
                    ckAgenciaAtiva.requestFocus();
                } else if (ke.getSource() == ckAgenciaAtiva){
                    if (ke.getKeyCode() == KeyEvent.VK_ENTER){
                        ckAgenciaAtiva.setSelected(true);
                    }
                    tEnderecoAgencia.requestFocus();
                }else if (ke.getSource() == tEnderecoAgencia) {
                    bSalvar.requestFocus();
                } else if (ke.getSource() == bSalvar && ke.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (!salvar()) {
                        tMensagem.setText("Informacoes invalidas!");
                    } else {
                        tMensagem.setText("Agencia cadastrada com sucesso!");
                    }
                    mostra();
                }
            }
        }

        @Override
        public void keyReleased(KeyEvent ke) {

        }

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bConsultarAgencia;
    private javax.swing.JButton bDesativar;
    private javax.swing.JButton bLimpar;
    private javax.swing.JButton bReativar;
    private javax.swing.JButton bSalvar;
    private javax.swing.JCheckBox ckAgenciaAtiva;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lCnpjAgencia;
    private javax.swing.JLabel lCodigoAgencia;
    private javax.swing.JLabel lEnderecoAgencia;
    private javax.swing.JLabel lNomeAgencia;
    private javax.swing.JPanel pAgencia;
    private javax.swing.JPanel pButtons;
    private javax.swing.JFormattedTextField tCnpjAgencia;
    private javax.swing.JTextField tCodigoAgencia;
    private javax.swing.JTextField tEnderecoAgencia;
    private javax.swing.JLabel tMensagem;
    private javax.swing.JTextField tNomeAgencia;
    // End of variables declaration//GEN-END:variables
    private AgenciaBean agencia;
    private final TrataBotoes trataBotoes = new TrataBotoes();
    private final TrataFoco trataFoco = new TrataFoco();
    private final TrataTeclas trataTeclas = new TrataTeclas();
}
